<?php
/**
 * Created by PhpStorm.
 * User: zhanglihe
 * Date: 17/11/2
 * Time: 下午2:33
 */
namespace App\Service;

use App\Service\baofu\Entity\PostMasterEntity;
use App\Service\baofu\Entity\RiskInfoEntity;
use App\Service\baofu\Entity\TerminalInfoEntity;
use App\Service\baofu\SecurityUtil\JuheSignatureUtils;
use App\Service\baofu\Util\HttpClient;
use App\Service\baofu\Util\Tools;
use Carbon\Carbon;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Http\Request;


class Baofu
{

    protected $request;
    private $merId = '1285873';
    private $terId = '92785';

    private $Version = "4.0.0.0";

    private $KEY_PWD = "568239";

    private $POST_URL = 'https://juhe.baofoo.com/api';

    private $PFX_FILE_PATH ;

    private $CER_FILE_PATH ;
    private $BF_FILE_PATH ;

    private $wx_appid  =  'wx9ebdcac23b1d3331';

    private $wx_sub =  '770733312';

    private $ali_sub =  '2088370470724721';

    private $ali_appid = '';

    private $Notify_Url = "https://ylz.yimitongxun.com/api/payment/notify";

    public function __construct(Request $request){
        $this->request = $request;
        $this->CER_FILE_PATH = app_path('Service/baofu/CerFile/gongyao.cer');
        $this->PFX_FILE_PATH = app_path('Service/baofu/CerFile/siyao.pfx');
        $this->BF_FILE_PATH = app_path('Service/baofu/CerFile/baofu.cer');
    }

    public function createOrder($order,$user){
        $txnAmt=$order->pay_amt*100;//用户实际付款金额
        $totalAmt=$order->pay_amt*100;//订单总金额
        $merId= $this->merId;
        $terId = $this->terId;
        if($order->pay_channel == 'wx_lite'){
            $payCode = "WECHAT_JSAPI";//"WECHAT_JSAPI";
            $subMchId=$this->wx_sub;
            $sub_appid=$this->wx_appid;
        }else{
            $sub_appid=$user->alipay_id;
            $subMchId=$this->ali_sub;
            $payCode = 'ALIPAY_JSAPI';
        }
        $Method = "unified_order";
///微信支付参数。
        $buyer_id=$sub_openid=$user->openid;;
        $Biz_Content = array();
//        $Biz_Content["agentMerId"] ="";
//        $Biz_Content["agentTerId"] ="";
        $Biz_Content["merId"] = $this->merId;
        $Biz_Content["terId"] = $this->terId;
        $Biz_Content["outTradeNo"] = $order->order_no;
        $Biz_Content["txnAmt"] = (int)$txnAmt;
        $Biz_Content["txnTime"] = date("YmdHis");
        $Biz_Content["totalAmt"] =(int)$totalAmt;
        $Biz_Content["timeExpire"] = "300";//订单支付的有效时间，单位：分钟
        $Biz_Content["prodType"] = "ORDINARY";//SHARING:分账产品,ORDINARY:普通产品
        $Biz_Content["payCode"] = $payCode;
        $Pay_Extend = array();
        if(substr($payCode,0, strlen("WECHAT")) == "WECHAT"){
            ///微信支付属性-公共属性
            $Pay_Extend["body"] = $order->goods_title;
            ////terminal_info 终端信息参数     支付方式为：WECHAT_MICROPAY该字段必填
            $Deviceid =$order->device_id;///终端设备号
            $Terminal_Info = new TerminalInfoEntity($payCode,$Deviceid);
            if($payCode == "WECHAT_JSAPI"){
                $Pay_Extend["sub_appid"] = $sub_appid;
                $Pay_Extend["sub_openid"] = $sub_openid;
            }else if($payCode == "WECHAT_MICROPAY"){
                $Pay_Extend["terminal_info"] = $Terminal_Info;
            }
        }else if(substr($payCode,0, strlen("ALIPAY")) == "ALIPAY"){
            $subMchId= $this->ali_sub;
            $Biz_Content['pageUrl'] = $order->pageUrl;
            $Pay_Extend["subject"] =  $order->goods_title;
            $Pay_Extend["area_info"] = "";
            ////terminal_info 终端信息参数     支付方式为：WECHAT_MICROPAY该字段必填
            $Deviceid =$order->device_id;///终端设备号
            $Terminal_Info = new TerminalInfoEntity($payCode,$Deviceid);
            if($payCode == "ALIPAY_JSAPI"){
                $Pay_Extend["buyer_id"] = $user->alipay_id;
            }else if($payCode == "ALIPAY_MICROPAY"){
                $Pay_Extend["terminal_info"] = $Terminal_Info;
            }
        }
        $Biz_Content["payExtend"] = $Pay_Extend;
        $Biz_Content["subMchId"]  = $subMchId ;
        $Biz_Content["notifyUrl"] = $this->Notify_Url;
//        $Biz_Content["forbidCredit"] = "0";//1：禁止,0：不禁止;不传默认为0

        $Rie = new RiskInfoEntity();
        $Rie->setLocationPoint("");//空值
        $Rie->setClientIp($this->request->ip());
        $Biz_Content["riskInfo"] = $Rie;
        $PostParm = new PostMasterEntity();
        $BizContent = json_encode($Biz_Content);
        $PostParm->setBizContent($BizContent);
        $PostParm->setMerId($merId);
        $PostParm->setTerId($terId);
        $PostParm->setMethod($Method);
        $SignStr = JuheSignatureUtils::Sign($BizContent, $this->PFX_FILE_PATH,$this->KEY_PWD);
        $PostParm->setSignStr($SignStr);
        $PostString  =  HttpClient::Post($PostParm, $this->POST_URL);
        $Post_Json = json_decode($PostString,true);
        if(!array_key_exists("returnCode",$Post_Json)){
            throw new \Exception("缺少returnCode参数！");
        }
        if(!array_key_exists("dataContent",$Post_Json)){
            throw new \Exception("缺少dataContent参数！");
        }
        if($Post_Json["returnCode"] === "SUCCESS") {
            if (empty ($Post_Json["dataContent"])) {
                throw new \Exception("返回值dataContent为空！");
            }
            if (!isset($Post_Json["signStr"]) && empty($Post_Json["signStr"])) {
                throw new \Exception("signStr参数不存在或为空！");
            }
            if (JuheSignatureUtils::VerifySign($Post_Json["dataContent"], $this->BF_FILE_PATH, $Post_Json["signStr"])) {
                return json_decode($Post_Json["dataContent"],true);
            }
        }
        Log::info('create-order-error'.json_encode($Post_Json));
        throw new \Exception("支付异常");
    }


    public function signNotify($data,$sign){
        if (JuheSignatureUtils::VerifySign($data, $this->BF_FILE_PATH, $sign)) {
            return true;
        }
        return false;
    }


    /**退款
     * @return void
     */
    public function refund($data){
        $Method = "order_refund";
        $Biz_Content = array();
        $Biz_Content["agentMerId"] ="";
        $Biz_Content["agentTerId"] ="";
        $Biz_Content["merId"] = $this->merId;
        $Biz_Content["terId"] = $this->terId;
        $Biz_Content['originTradeNo'] = $data['payment_id'];
        $Biz_Content['outTradeNo'] = $data['refund_no'];
        $Biz_Content["txnTime"] = date('YmdHis');
        $Biz_Content["notifyUrl"] = $this->Notify_Url;//
        $Biz_Content["refundAmt"] = $Biz_Content['totalAmt'] = (int)($data['amount']*100);
        $Biz_Content['refundReason'] = $data['remark'];
        $PostParm = new PostMasterEntity();
        $BizContent = json_encode($Biz_Content);
        $PostParm->setBizContent($BizContent);
        $PostParm->setMerId($this->merId);
        $PostParm->setTerId($this->terId);
        $PostParm->setMethod($Method);
        $SignStr = JuheSignatureUtils::Sign($BizContent, $this->PFX_FILE_PATH,$this->KEY_PWD);
        $PostParm->setSignStr($SignStr);
        Log::info('参数发起',[$PostParm]);
        $PostString  =  HttpClient::Post($PostParm, "https://juhe.baofoo.com/api");;
        $Post_Json = json_decode($PostString,true);
        Log::info('发起退款',[$Post_Json]);
        if(!array_key_exists("returnCode",$Post_Json)){
            throw new \Exception("缺少returnCode参数！");
        }
        if(!array_key_exists("dataContent",$Post_Json)){
            throw new \Exception("缺少dataContent参数！");
        }
        if($Post_Json["returnCode"] === "SUCCESS") {
            if (empty ($Post_Json["dataContent"])) {
                throw new \Exception("返回值dataContent为空！");
            }
            if (!isset($Post_Json["signStr"]) && empty($Post_Json["signStr"])) {
                throw new \Exception("signStr参数不存在或为空！");
            }
            if (JuheSignatureUtils::VerifySign($Post_Json["dataContent"], $this->BF_FILE_PATH, $Post_Json["signStr"])) {
                return $Post_Json['dataContent'];
            }
        }
        throw new \Exception("退款异常");
    }


    /**
     * 查询投诉单列表
     * @param array $params 查询参数
     * @return array|mixed
     * @throws \Exception
     */
    public function queryComplaintList($params = [])
    {
        // 接口服务类型
        $Method = "complaint_query_list";

        // 使用新的接口地址
        $url = "https://juhe.baofoo.com/mch-service/api";

        // 设置默认参数
        $defaultParams = [
            'merId' => $this->merId,
            'terId' => $this->terId,
            'limit' => 10,
            'offset' => 0
        ];

        // 合并参数
        $requestParams = array_merge($defaultParams, $params);

        // 参数验证
        if (!isset($requestParams['beginDate']) || !isset($requestParams['endDate'])) {
            throw new \Exception("开始日期和结束日期为必填参数");
        }

        // 验证日期格式
        $beginDate = \DateTime::createFromFormat('Y-m-d H:i:s', $requestParams['beginDate']);
        $endDate = \DateTime::createFromFormat('Y-m-d H:i:s', $requestParams['endDate']);

        if (!$beginDate || !$endDate) {
            throw new \Exception("日期格式错误，应为 yyyy-MM-dd HH:mm:ss");
        }

        // 验证日期跨度不超过30天
        $interval = $beginDate->diff($endDate);
        if ($interval->days > 30) {
            throw new \Exception("查询日期跨度不能超过30天");
        }

        // 验证limit范围 [1,50]
        if (!is_numeric($requestParams['limit']) || $requestParams['limit'] < 1 || $requestParams['limit'] > 50) {
            throw new \Exception("分页大小limit必须是1-50之间的整数");
        }

        // 验证offset为非负整数
        if (!is_numeric($requestParams['offset']) || $requestParams['offset'] < 0) {
            throw new \Exception("分页开始位置offset必须是非负整数");
        }

        // 确保参数类型正确
        $requestParams['limit'] = (int)$requestParams['limit'];
        $requestParams['offset'] = (int)$requestParams['offset'];

        // 构建业务内容
        $BizContent = json_encode($requestParams, JSON_UNESCAPED_UNICODE);

        // 签名
        $SignStr = JuheSignatureUtils::Sign($BizContent, $this->PFX_FILE_PATH, $this->KEY_PWD);

        // 构建请求参数
        $PostParm = new PostMasterEntity();
        $PostParm->setBizContent($BizContent);
        $PostParm->setMerId($requestParams['merId']);
        $PostParm->setTerId($requestParams['terId']);
        $PostParm->setMethod($Method);
        $PostParm->setSignStr($SignStr);


        // 发送请求
        try {
            $PostString = HttpClient::Post($PostParm, $url);
            if (empty($PostString)) {
                throw new \Exception("投诉查询列表请求返回异常");
            }

            $Post_Json = json_decode($PostString, true);

            // 根据返回格式处理
            if (isset($Post_Json['returnCode'])) {
                if ($Post_Json["returnCode"] === "SUCCESS") {
                    if (isset($Post_Json["dataContent"]) && !empty($Post_Json["dataContent"])) {
                        if (isset($Post_Json["signStr"]) && !empty($Post_Json["signStr"])) {
                            // 验证签名
                            if (JuheSignatureUtils::VerifySign($Post_Json["dataContent"], $this->BF_FILE_PATH, $Post_Json["signStr"])) {
                                $result = json_decode($Post_Json["dataContent"], true);
                                if (isset($result['resultCode'])) {
                                    if ($result['resultCode'] === 'SUCCESS') {
                                        return $result;
                                    } else {
                                        $errMsg = isset($result['errMsg']) ? $result['errMsg'] : '业务处理失败';
                                        throw new \Exception("业务处理失败：" . $errMsg);
                                    }
                                }
                                return $result;
                            } else {
                                throw new \Exception("返回数据签名验证失败！");
                            }
                        } else {
                            throw new \Exception("缺少签名信息");
                        }
                    } else {
                        // 没有dataContent，直接返回
                        return $Post_Json;
                    }
                } else {
                    $errorMsg = isset($Post_Json['returnMsg']) ? $Post_Json['returnMsg'] : '系统处理失败';
                    throw new \Exception("系统处理失败：" . $errorMsg . " (Code: " . $Post_Json["returnCode"] . ")");
                }
            } else if (isset($Post_Json['resultCode'])) {
                if ($Post_Json['resultCode'] === 'SUCCESS') {
                    return $Post_Json;
                } else {
                    $errorMsg = isset($Post_Json['errMsg']) ? $Post_Json['errMsg'] : '业务处理失败';
                    throw new \Exception("业务处理失败：" . $errorMsg);
                }
            } else {
                throw new \Exception("返回数据格式未知：" . $PostString);
            }
        } catch (\Exception $e) {
            Log::error("投诉查询列表异常：" . $e->getMessage());
            throw $e;
        }
    }

    /**
     * 查询投诉单详情
     * @param string $complaintId 投诉单号
     * @param array $extraParams 额外参数（如代理商商户号等）
     * @return array|mixed
     * @throws \Exception
     */
    public function queryComplaintDetail($complaintId, $extraParams = [])
    {
        // 接口服务类型
        $Method = "complaint_query_detail";

        // 使用新的接口地址
        $url = "https://juhe.baofoo.com/mch-service/api";

        // 验证投诉单号
        if (empty($complaintId)) {
            throw new \Exception("投诉单号不能为空");
        }

        // 设置默认参数
        $requestParams = [
            'merId' => $this->merId,
            'terId' => $this->terId,
            'complaintId' => $complaintId
        ];

        // 合并额外参数
        $requestParams = array_merge($requestParams, $extraParams);

        // 构建业务内容
        $BizContent = json_encode($requestParams, JSON_UNESCAPED_UNICODE);

        // 签名
        $SignStr = JuheSignatureUtils::Sign($BizContent, $this->PFX_FILE_PATH, $this->KEY_PWD);

        // 构建请求参数
        $PostParm = new PostMasterEntity();
        $PostParm->setBizContent($BizContent);
        $PostParm->setMerId($requestParams['merId']);
        $PostParm->setTerId($requestParams['terId']);
        $PostParm->setMethod($Method);
        $PostParm->setSignStr($SignStr);

        // 记录详细请求日志
        // 发送请求
        try {
            $PostString = HttpClient::Post($PostParm, $url);
            if (empty($PostString)) {
                throw new \Exception("投诉查询详情请求返回异常");
            }
            $Post_Json = json_decode($PostString, true);
            // 根据返回格式处理
            if (isset($Post_Json['returnCode'])) {
                if ($Post_Json["returnCode"] === "SUCCESS") {
                    // 检查是否包含数字信封和加密数据
                    if (isset($Post_Json["dgtlEnvlp"]) && isset($Post_Json["dataContent"])) {
                        // 返回包含数字信封的完整响应，供后续解密使用
                        return $Post_Json;
                    }

                    if (isset($Post_Json["dataContent"]) && !empty($Post_Json["dataContent"])) {
                        if (isset($Post_Json["signStr"]) && !empty($Post_Json["signStr"])) {
                            // 验证签名
                            if (JuheSignatureUtils::VerifySign($Post_Json["dataContent"], $this->BF_FILE_PATH, $Post_Json["signStr"])) {
                                $result = json_decode($Post_Json["dataContent"], true);
                                if (isset($result['resultCode'])) {
                                    if ($result['resultCode'] === 'SUCCESS') {
                                        return $result;
                                    } else {
                                        $errMsg = isset($result['errMsg']) ? $result['errMsg'] : '业务处理失败';
                                        throw new \Exception("业务处理失败：" . $errMsg);
                                    }
                                }
                                return $result;
                            } else {
                                throw new \Exception("返回数据签名验证失败！");
                            }
                        } else {
                            throw new \Exception("缺少签名信息");
                        }
                    } else {
                        // 没有dataContent，直接返回
                        return $Post_Json;
                    }
                } else {
                    $errorMsg = isset($Post_Json['returnMsg']) ? $Post_Json['returnMsg'] : '系统处理失败';
                    throw new \Exception("系统处理失败：" . $errorMsg . " (Code: " . $Post_Json["returnCode"] . ")");
                }
            } else if (isset($Post_Json['resultCode'])) {
                if ($Post_Json['resultCode'] === 'SUCCESS') {
                    return $Post_Json;
                } else {
                    $errorMsg = isset($Post_Json['errMsg']) ? $Post_Json['errMsg'] : '业务处理失败';
                    throw new \Exception("业务处理失败：" . $errorMsg);
                }
            } else {
                throw new \Exception("返回数据格式未知：" . $PostString);
            }
        } catch (\Exception $e) {
            Log::error("投诉查询详情异常：" . $e->getMessage());
            throw $e;
        }
    }


    /**
     * 查询投诉协商历史
     * @param string $complaintId 投诉单号
     * @param array $params 查询参数（包含分页等）
     * @param array $extraParams 额外参数（如代理商商户号等）
     * @return array|mixed
     * @throws \Exception
     */
    public function queryNegotiationHistory($complaintId, $params = [], $extraParams = [])
    {
        // 接口服务类型
        $Method = "negotiation_history";

        // 使用新的接口地址
        $url = "https://juhe.baofoo.com/mch-service/api";

        // 验证投诉单号
        if (empty($complaintId)) {
            throw new \Exception("投诉单号不能为空");
        }

        // 设置默认参数
        $defaultParams = [
            'merId' => $this->merId,
            'terId' => $this->terId,
            'complaintId' => $complaintId,
            'limit' => 100,  // 默认100条
            'offset' => 0
        ];

        // 合并参数
        $requestParams = array_merge($defaultParams, $params, $extraParams);

        // 参数验证
        // 验证limit范围 [1,300]
        if (!is_numeric($requestParams['limit']) || $requestParams['limit'] < 1 || $requestParams['limit'] > 300) {
            throw new \Exception("分页大小limit必须是1-300之间的整数");
        }

        // 验证offset为非负整数
        if (!is_numeric($requestParams['offset']) || $requestParams['offset'] < 0) {
            throw new \Exception("分页开始位置offset必须是非负整数");
        }

        // 确保参数类型正确
        $requestParams['limit'] = (int)$requestParams['limit'];
        $requestParams['offset'] = (int)$requestParams['offset'];

        // 构建业务内容
        $BizContent = json_encode($requestParams, JSON_UNESCAPED_UNICODE);

        // 签名
        $SignStr = JuheSignatureUtils::Sign($BizContent, $this->PFX_FILE_PATH, $this->KEY_PWD);

        // 构建请求参数
        $PostParm = new PostMasterEntity();
        $PostParm->setBizContent($BizContent);
        $PostParm->setMerId($requestParams['merId']);
        $PostParm->setTerId($requestParams['terId']);
        $PostParm->setMethod($Method);
        $PostParm->setSignStr($SignStr);
        // 发送请求
        try {
            $PostString = HttpClient::Post($PostParm, $url);
            Log::info("查询协商历史返回完整响应：" . $PostString);

            if (empty($PostString)) {
                throw new \Exception("查询协商历史请求返回异常");
            }

            $Post_Json = json_decode($PostString, true);

            // 根据返回格式处理
            if (isset($Post_Json['returnCode'])) {
                if ($Post_Json["returnCode"] === "SUCCESS") {
                    if (isset($Post_Json["dataContent"]) && !empty($Post_Json["dataContent"])) {
                        if (isset($Post_Json["signStr"]) && !empty($Post_Json["signStr"])) {
                            // 验证签名
                            if (JuheSignatureUtils::VerifySign($Post_Json["dataContent"], $this->BF_FILE_PATH, $Post_Json["signStr"])) {
                                $result = json_decode($Post_Json["dataContent"], true);
                                if (isset($result['resultCode'])) {
                                    if ($result['resultCode'] === 'SUCCESS') {
                                        return $result;
                                    } else {
                                        $errMsg = isset($result['errMsg']) ? $result['errMsg'] : '业务处理失败';
                                        throw new \Exception("业务处理失败：" . $errMsg);
                                    }
                                }
                                return $result;
                            } else {
                                throw new \Exception("返回数据签名验证失败！");
                            }
                        } else {
                            throw new \Exception("缺少签名信息");
                        }
                    } else {
                        // 没有dataContent，直接返回
                        return $Post_Json;
                    }
                } else {
                    $errorMsg = isset($Post_Json['returnMsg']) ? $Post_Json['returnMsg'] : '系统处理失败';
                    throw new \Exception("系统处理失败：" . $errorMsg . " (Code: " . $Post_Json["returnCode"] . ")");
                }
            } else if (isset($Post_Json['resultCode'])) {
                if ($Post_Json['resultCode'] === 'SUCCESS') {
                    return $Post_Json;
                } else {
                    $errorMsg = isset($Post_Json['errMsg']) ? $Post_Json['errMsg'] : '业务处理失败';
                    throw new \Exception("业务处理失败：" . $errorMsg);
                }
            } else {
                throw new \Exception("返回数据格式未知：" . $PostString);
            }
        } catch (\Exception $e) {
            Log::error("查询协商历史异常：" . $e->getMessage());
            throw $e;
        }
    }

    /**
     * 投诉回复接口
     * @param string $complaintId 投诉单号
     * @param string $responseContent 回复内容
     * @param array $params 其他参数（包括图片、跳转链接等）
     * @param array $extraParams 额外参数（如代理商商户号等）
     * @return array|mixed
     * @throws \Exception
     */
    public function complaintResponse($complaintId, $responseContent, $params = [], $extraParams = [])
    {
        // 接口服务类型
        $Method = "complaint_response";

        // 使用新的接口地址
        $url = "https://juhe.baofoo.com/mch-service/api";

        // 验证必填参数
        if (empty($complaintId)) {
            throw new \Exception("投诉单号不能为空");
        }

        if (empty($responseContent)) {
            throw new \Exception("回复内容不能为空");
        }

        // 验证回复内容长度
        if (mb_strlen($responseContent) > 200) {
            throw new \Exception("回复内容不能超过200个字符");
        }

        // 设置默认参数
        $defaultParams = [
            'merId' => $this->merId,
            'terId' => $this->terId,
            'complaintId' => $complaintId,
            'responseContent' => $responseContent
        ];

        // 合并参数
        $requestParams = array_merge($defaultParams, $params, $extraParams);

        // 验证跳转链接和跳转文案的逻辑
        if (isset($requestParams['jumpUrl']) && !empty($requestParams['jumpUrl'])) {
            // 如果有跳转链接，跳转文案也必须提供
            if (!isset($requestParams['jumpUrlText']) || empty($requestParams['jumpUrlText'])) {
                throw new \Exception("跳转链接和跳转链接文案必须同时提供");
            }
        }

        // 验证图片数量不超过4张
        if (isset($requestParams['responseImages']) && is_array($requestParams['responseImages'])) {
            if (count($requestParams['responseImages']) > 4) {
                throw new \Exception("最多只能上传4张图片凭证");
            }
        }

        // 构建业务内容
        $BizContent = json_encode($requestParams, JSON_UNESCAPED_UNICODE);

        // 签名
        $SignStr = JuheSignatureUtils::Sign($BizContent, $this->PFX_FILE_PATH, $this->KEY_PWD);

        // 构建请求参数
        $PostParm = new PostMasterEntity();
        $PostParm->setBizContent($BizContent);
        $PostParm->setMerId($requestParams['merId']);
        $PostParm->setTerId($requestParams['terId']);
        $PostParm->setMethod($Method);
        $PostParm->setSignStr($SignStr);

        // 发送请求
        try {
            $PostString = HttpClient::Post($PostParm, $url);
            Log::info("投诉回复接口返回完整响应：" . $PostString);

            if (empty($PostString)) {
                throw new \Exception("投诉回复请求返回异常");
            }

            $Post_Json = json_decode($PostString, true);

            // 根据返回格式处理
            if (isset($Post_Json['returnCode'])) {
                if ($Post_Json["returnCode"] === "SUCCESS") {
                    if (isset($Post_Json["dataContent"]) && !empty($Post_Json["dataContent"])) {
                        if (isset($Post_Json["signStr"]) && !empty($Post_Json["signStr"])) {
                            // 验证签名
                            if (JuheSignatureUtils::VerifySign($Post_Json["dataContent"], $this->BF_FILE_PATH, $Post_Json["signStr"])) {
                                $result = json_decode($Post_Json["dataContent"], true);
                                if (isset($result['resultCode'])) {
                                    if ($result['resultCode'] === 'SUCCESS') {
                                        return $result;
                                    } else {
                                        $errMsg = isset($result['errMsg']) ? $result['errMsg'] : '业务处理失败';
                                        throw new \Exception("业务处理失败：" . $errMsg);
                                    }
                                }
                                return $result;
                            } else {
                                throw new \Exception("返回数据签名验证失败！");
                            }
                        } else {
                            throw new \Exception("缺少签名信息");
                        }
                    } else {
                        // 没有dataContent，直接返回
                        return $Post_Json;
                    }
                } else {
                    $errorMsg = isset($Post_Json['returnMsg']) ? $Post_Json['returnMsg'] : '系统处理失败';
                    throw new \Exception("系统处理失败：" . $errorMsg . " (Code: " . $Post_Json["returnCode"] . ")");
                }
            } else if (isset($Post_Json['resultCode'])) {
                if ($Post_Json['resultCode'] === 'SUCCESS') {
                    return $Post_Json;
                } else {
                    $errorMsg = isset($Post_Json['errMsg']) ? $Post_Json['errMsg'] : '业务处理失败';
                    throw new \Exception("业务处理失败：" . $errorMsg);
                }
            } else {
                throw new \Exception("返回数据格式未知：" . $PostString);
            }
        } catch (\Exception $e) {
            Log::error("投诉回复接口异常：" . $e->getMessage());
            throw $e;
        }
    }


    /**
     * 上传投诉反馈图片
     * @param string $complaintId 投诉单号
     * @param string $imagePath 图片文件路径
     * @param array $extraParams 额外参数（如代理商商户号等）
     * @return array|mixed
     * @throws \Exception
     */
    public function uploadComplaintImage($complaintId, $imagePath, $extraParams = [])
    {
        // 接口服务类型
        $Method = "complaint_images_upload";

        // 使用新的接口地址
        $url = "https://juhe.baofoo.com/mch-service/api";

        // 验证必填参数
        if (empty($complaintId)) {
            throw new \Exception("投诉单号不能为空");
        }

        if (empty($imagePath)) {
            throw new \Exception("图片路径不能为空");
        }

        // 检查文件是否存在
        if (!file_exists($imagePath)) {
            throw new \Exception("图片文件不存在");
        }

        // 检查文件大小（不能超过2M）
        $fileSize = filesize($imagePath);
        if ($fileSize > 2 * 1024 * 1024) {
            throw new \Exception("图片文件大小不能超过2M");
        }

        // 检查文件格式
        $allowedExtensions = ['jpg', 'jpeg', 'png', 'bmp'];
        $fileExtension = strtolower(pathinfo($imagePath, PATHINFO_EXTENSION));
        if (!in_array($fileExtension, $allowedExtensions)) {
            throw new \Exception("图片格式只支持jpg、png、bmp");
        }

        // 读取图片文件并进行Base64编码
        $imageData = file_get_contents($imagePath);
        if ($imageData === false) {
            throw new \Exception("读取图片文件失败");
        }

        $base64Image = base64_encode($imageData);

        // 计算文件SHA256摘要
        $sha256 = hash('sha256', $imageData);

        // 获取文件名
        $fileName = basename($imagePath);

        // 设置默认参数
        $requestParams = [
            'merId' => $this->merId,
            'terId' => $this->terId,
            'complaintId' => $complaintId,
            'file' => $base64Image,
            'metaReq' => [
                'fileName' => $fileName,
                'sha256' => $sha256
            ]
        ];

        // 合并额外参数
        $requestParams = array_merge($requestParams, $extraParams);

        // 构建业务内容
        $BizContent = json_encode($requestParams, JSON_UNESCAPED_UNICODE);

        // 签名
        $SignStr = JuheSignatureUtils::Sign($BizContent, $this->PFX_FILE_PATH, $this->KEY_PWD);

        // 构建请求参数
        $PostParm = new PostMasterEntity();
        $PostParm->setBizContent($BizContent);
        $PostParm->setMerId($requestParams['merId']);
        $PostParm->setTerId($requestParams['terId']);
        $PostParm->setMethod($Method);
        $PostParm->setSignStr($SignStr);

        // 发送请求
        try {
            $PostString = HttpClient::Post($PostParm, $url);
            Log::info("上传投诉图片接口返回完整响应：" . $PostString);

            if (empty($PostString)) {
                throw new \Exception("上传投诉图片请求返回异常");
            }

            $Post_Json = json_decode($PostString, true);

            // 根据返回格式处理
            if (isset($Post_Json['returnCode'])) {
                if ($Post_Json["returnCode"] === "SUCCESS") {
                    if (isset($Post_Json["dataContent"]) && !empty($Post_Json["dataContent"])) {
                        if (isset($Post_Json["signStr"]) && !empty($Post_Json["signStr"])) {
                            // 验证签名
                            if (JuheSignatureUtils::VerifySign($Post_Json["dataContent"], $this->BF_FILE_PATH, $Post_Json["signStr"])) {
                                $result = json_decode($Post_Json["dataContent"], true);
                                if (isset($result['resultCode'])) {
                                    if ($result['resultCode'] === 'SUCCESS') {
                                        return $result;
                                    } else {
                                        $errMsg = isset($result['errMsg']) ? $result['errMsg'] : '业务处理失败';
                                        throw new \Exception("业务处理失败：" . $errMsg);
                                    }
                                }
                                return $result;
                            } else {
                                throw new \Exception("返回数据签名验证失败！");
                            }
                        } else {
                            throw new \Exception("缺少签名信息");
                        }
                    } else {
                        // 没有dataContent，直接返回
                        return $Post_Json;
                    }
                } else {
                    $errorMsg = isset($Post_Json['returnMsg']) ? $Post_Json['returnMsg'] : '系统处理失败';
                    throw new \Exception("系统处理失败：" . $errorMsg . " (Code: " . $Post_Json["returnCode"] . ")");
                }
            } else if (isset($Post_Json['resultCode'])) {
                if ($Post_Json['resultCode'] === 'SUCCESS') {
                    return $Post_Json;
                } else {
                    $errorMsg = isset($Post_Json['errMsg']) ? $Post_Json['errMsg'] : '业务处理失败';
                    throw new \Exception("业务处理失败：" . $errorMsg);
                }
            } else {
                throw new \Exception("返回数据格式未知：" . $PostString);
            }
        } catch (\Exception $e) {
            Log::error("上传投诉图片接口异常：" . $e->getMessage());
            throw $e;
        }
    }

    /**
     * 上传投诉反馈图片（通过图片二进制数据）
     * @param string $complaintId 投诉单号
     * @param string $imageData 图片二进制数据
     * @param string $fileName 文件名
     * @param array $extraParams 额外参数（如代理商商户号等）
     * @return array|mixed
     * @throws \Exception
     */
    public function uploadComplaintImageData($complaintId, $imageData, $fileName, $extraParams = [])
    {
        // 接口服务类型
        $Method = "complaint_images_upload";

        // 使用新的接口地址
        $url = "https://juhe.baofoo.com/mch-service/api";

        // 验证必填参数
        if (empty($complaintId)) {
            throw new \Exception("投诉单号不能为空");
        }

        if (empty($imageData)) {
            throw new \Exception("图片数据不能为空");
        }

        if (empty($fileName)) {
            throw new \Exception("文件名不能为空");
        }

        // 检查文件大小（不能超过2M）
        $fileSize = strlen($imageData);
        if ($fileSize > 2 * 1024 * 1024) {
            throw new \Exception("图片文件大小不能超过2M");
        }

        // 检查文件格式
        $allowedExtensions = ['jpg', 'jpeg', 'png', 'bmp'];
        $fileExtension = strtolower(pathinfo($fileName, PATHINFO_EXTENSION));
        if (!in_array($fileExtension, $allowedExtensions)) {
            throw new \Exception("图片格式只支持jpg、png、bmp");
        }

        // 进行Base64编码
        $base64Image = base64_encode($imageData);

        // 计算文件SHA256摘要
        $sha256 = hash('sha256', $imageData);

        // 设置默认参数
        $requestParams = [
            'merId' => $this->merId,
            'terId' => $this->terId,
            'complaintId' => $complaintId,
            'file' => $base64Image,
            'metaReq' => [
                'fileName' => $fileName,
                'sha256' => $sha256
            ]
        ];

        // 合并额外参数
        $requestParams = array_merge($requestParams, $extraParams);

        // 构建业务内容
        $BizContent = json_encode($requestParams, JSON_UNESCAPED_UNICODE);

        // 签名
        $SignStr = JuheSignatureUtils::Sign($BizContent, $this->PFX_FILE_PATH, $this->KEY_PWD);

        // 构建请求参数
        $PostParm = new PostMasterEntity();
        $PostParm->setBizContent($BizContent);
        $PostParm->setMerId($requestParams['merId']);
        $PostParm->setTerId($requestParams['terId']);
        $PostParm->setMethod($Method);
        $PostParm->setSignStr($SignStr);

        // 发送请求
        try {
            $PostString = HttpClient::Post($PostParm, $url);
            Log::info("上传投诉图片接口返回完整响应：" . $PostString);

            if (empty($PostString)) {
                throw new \Exception("上传投诉图片请求返回异常");
            }

            $Post_Json = json_decode($PostString, true);

            // 根据返回格式处理
            if (isset($Post_Json['returnCode'])) {
                if ($Post_Json["returnCode"] === "SUCCESS") {
                    if (isset($Post_Json["dataContent"]) && !empty($Post_Json["dataContent"])) {
                        if (isset($Post_Json["signStr"]) && !empty($Post_Json["signStr"])) {
                            // 验证签名
                            if (JuheSignatureUtils::VerifySign($Post_Json["dataContent"], $this->BF_FILE_PATH, $Post_Json["signStr"])) {
                                $result = json_decode($Post_Json["dataContent"], true);
                                if (isset($result['resultCode'])) {
                                    if ($result['resultCode'] === 'SUCCESS') {
                                        return $result;
                                    } else {
                                        $errMsg = isset($result['errMsg']) ? $result['errMsg'] : '业务处理失败';
                                        throw new \Exception("业务处理失败：" . $errMsg);
                                    }
                                }
                                return $result;
                            } else {
                                throw new \Exception("返回数据签名验证失败！");
                            }
                        } else {
                            throw new \Exception("缺少签名信息");
                        }
                    } else {
                        // 没有dataContent，直接返回
                        return $Post_Json;
                    }
                } else {
                    $errorMsg = isset($Post_Json['returnMsg']) ? $Post_Json['returnMsg'] : '系统处理失败';
                    throw new \Exception("系统处理失败：" . $errorMsg . " (Code: " . $Post_Json["returnCode"] . ")");
                }
            } else if (isset($Post_Json['resultCode'])) {
                if ($Post_Json['resultCode'] === 'SUCCESS') {
                    return $Post_Json;
                } else {
                    $errorMsg = isset($Post_Json['errMsg']) ? $Post_Json['errMsg'] : '业务处理失败';
                    throw new \Exception("业务处理失败：" . $errorMsg);
                }
            } else {
                throw new \Exception("返回数据格式未知：" . $PostString);
            }
        } catch (\Exception $e) {
            Log::error("上传投诉图片接口异常：" . $e->getMessage());
            throw $e;
        }
    }

    /**
     * 反馈投诉处理完成接口
     * @param string $complaintId 投诉单号
     * @param array $extraParams 额外参数（如代理商商户号、被诉商户号等）
     * @return array|mixed
     * @throws \Exception
     */
    public function complaintComplete($complaintId, $extraParams = [])
    {
        // 接口服务类型
        $Method = "complaint_complete";

        // 使用新的接口地址
        $url = "https://juhe.baofoo.com/mch-service/api";

        // 验证必填参数
        if (empty($complaintId)) {
            throw new \Exception("投诉单号不能为空");
        }

        // 设置默认参数
        $requestParams = [
            'merId' => $this->merId,
            'terId' => $this->terId,
            'complaintId' => $complaintId
        ];

        // 合并额外参数
        $requestParams = array_merge($requestParams, $extraParams);

        // 构建业务内容
        $BizContent = json_encode($requestParams, JSON_UNESCAPED_UNICODE);

        // 签名
        $SignStr = JuheSignatureUtils::Sign($BizContent, $this->PFX_FILE_PATH, $this->KEY_PWD);

        // 构建请求参数
        $PostParm = new PostMasterEntity();
        $PostParm->setBizContent($BizContent);
        $PostParm->setMerId($requestParams['merId']);
        $PostParm->setTerId($requestParams['terId']);
        $PostParm->setMethod($Method);
        $PostParm->setSignStr($SignStr);

        // 发送请求
        try {
            $PostString = HttpClient::Post($PostParm, $url);
            Log::info("反馈投诉处理完成接口返回完整响应：" . $PostString);

            if (empty($PostString)) {
                throw new \Exception("反馈投诉处理完成请求返回异常");
            }

            $Post_Json = json_decode($PostString, true);

            // 根据返回格式处理
            if (isset($Post_Json['returnCode'])) {
                if ($Post_Json["returnCode"] === "SUCCESS") {
                    if (isset($Post_Json["dataContent"]) && !empty($Post_Json["dataContent"])) {
                        if (isset($Post_Json["signStr"]) && !empty($Post_Json["signStr"])) {
                            // 验证签名
                            if (JuheSignatureUtils::VerifySign($Post_Json["dataContent"], $this->BF_FILE_PATH, $Post_Json["signStr"])) {
                                $result = json_decode($Post_Json["dataContent"], true);
                                if (isset($result['resultCode'])) {
                                    if ($result['resultCode'] === 'SUCCESS') {
                                        return $result;
                                    } else {
                                        $errMsg = isset($result['errMsg']) ? $result['errMsg'] : '业务处理失败';
                                        throw new \Exception("业务处理失败：" . $errMsg);
                                    }
                                }
                                return $result;
                            } else {
                                throw new \Exception("返回数据签名验证失败！");
                            }
                        } else {
                            throw new \Exception("缺少签名信息");
                        }
                    } else {
                        // 没有dataContent，直接返回
                        return $Post_Json;
                    }
                } else {
                    $errorMsg = isset($Post_Json['returnMsg']) ? $Post_Json['returnMsg'] : '系统处理失败';
                    throw new \Exception("系统处理失败：" . $errorMsg . " (Code: " . $Post_Json["returnCode"] . ")");
                }
            } else if (isset($Post_Json['resultCode'])) {
                if ($Post_Json['resultCode'] === 'SUCCESS') {
                    return $Post_Json;
                } else {
                    $errorMsg = isset($Post_Json['errMsg']) ? $Post_Json['errMsg'] : '业务处理失败';
                    throw new \Exception("业务处理失败：" . $errorMsg);
                }
            } else {
                throw new \Exception("返回数据格式未知：" . $PostString);
            }
        } catch (\Exception $e) {
            Log::error("反馈投诉处理完成接口异常：" . $e->getMessage());
            throw $e;
        }
    }

    /**
     * 图片下载接口
     * @param string $complaintId 投诉单号
     * @param string $mediaUrl 媒体文件请求url
     * @param array $extraParams 额外参数（如代理商商户号等）
     * @return array|mixed
     * @throws \Exception
     */
    public function downloadImage($complaintId, $mediaUrl, $extraParams = [])
    {
        // 接口服务类型
        $Method = "image_download";

        // 使用新的接口地址
        $url = "https://juhe.baofoo.com/mch-service/api";

        // 验证必填参数
        if (empty($complaintId)) {
            throw new \Exception("投诉单号不能为空");
        }

        if (empty($mediaUrl)) {
            throw new \Exception("媒体文件请求url不能为空");
        }

        // 设置默认参数
        $requestParams = [
            'merId' => $this->merId,
            'terId' => $this->terId,
            'complaintId' => $complaintId,
            'mediaUrl' => $mediaUrl
        ];

        // 合并额外参数
        $requestParams = array_merge($requestParams, $extraParams);

        // 构建业务内容
        $BizContent = json_encode($requestParams, JSON_UNESCAPED_UNICODE);

        // 签名
        $SignStr = JuheSignatureUtils::Sign($BizContent, $this->PFX_FILE_PATH, $this->KEY_PWD);

        // 构建请求参数
        $PostParm = new PostMasterEntity();
        $PostParm->setBizContent($BizContent);
        $PostParm->setMerId($requestParams['merId']);
        $PostParm->setTerId($requestParams['terId']);
        $PostParm->setMethod($Method);
        $PostParm->setSignStr($SignStr);

        // 发送请求
        try {
            $PostString = HttpClient::Post($PostParm, $url);
            Log::info("图片下载接口返回完整响应：" . $PostString);

            if (empty($PostString)) {
                throw new \Exception("图片下载请求返回异常");
            }

            $Post_Json = json_decode($PostString, true);

            // 根据返回格式处理
            if (isset($Post_Json['returnCode'])) {
                if ($Post_Json["returnCode"] === "SUCCESS") {
                    if (isset($Post_Json["dataContent"]) && !empty($Post_Json["dataContent"])) {
                        if (isset($Post_Json["signStr"]) && !empty($Post_Json["signStr"])) {
                            // 验证签名
                            if (JuheSignatureUtils::VerifySign($Post_Json["dataContent"], $this->BF_FILE_PATH, $Post_Json["signStr"])) {
                                $result = json_decode($Post_Json["dataContent"], true);
                                if (isset($result['resultCode'])) {
                                    if ($result['resultCode'] === 'SUCCESS') {
                                        return $result;
                                    } else {
                                        $errMsg = isset($result['errMsg']) ? $result['errMsg'] : '业务处理失败';
                                        throw new \Exception("业务处理失败：" . $errMsg);
                                    }
                                }
                                return $result;
                            } else {
                                throw new \Exception("返回数据签名验证失败！");
                            }
                        } else {
                            throw new \Exception("缺少签名信息");
                        }
                    } else {
                        // 没有dataContent，直接返回
                        return $Post_Json;
                    }
                } else {
                    $errorMsg = isset($Post_Json['returnMsg']) ? $Post_Json['returnMsg'] : '系统处理失败';
                    throw new \Exception("系统处理失败：" . $errorMsg . " (Code: " . $Post_Json["returnCode"] . ")");
                }
            } else if (isset($Post_Json['resultCode'])) {
                if ($Post_Json['resultCode'] === 'SUCCESS') {
                    return $Post_Json;
                } else {
                    $errorMsg = isset($Post_Json['errMsg']) ? $Post_Json['errMsg'] : '业务处理失败';
                    throw new \Exception("业务处理失败：" . $errorMsg);
                }
            } else {
                throw new \Exception("返回数据格式未知：" . $PostString);
            }
        } catch (\Exception $e) {
            Log::error("图片下载接口异常：" . $e->getMessage());
            throw $e;
        }
    }

    /**
     * 保存下载的图片到本地文件
     * @param string $complaintId 投诉单号
     * @param string $mediaUrl 媒体文件请求url
     * @param string $savePath 保存路径
     * @param array $extraParams 额外参数
     * @return bool
     * @throws \Exception
     */
    public function downloadImageToFile($complaintId, $mediaUrl, $savePath, $extraParams = [])
    {
        try {
            $result = $this->downloadImage($complaintId, $mediaUrl, $extraParams);
            return $result;
            if (isset($result['resultCode']) && $result['resultCode'] === 'SUCCESS') {
                // 检查返回的image数据
                if (!isset($result['image']) || empty($result['image'])) {
                    throw new \Exception("返回的图片数据为空");
                }

                // base64解码图片数据
                $imageData = base64_decode($result['image']);
                if ($imageData === false) {
                    throw new \Exception("图片数据解码失败");
                }

                // 确保保存目录存在
                $directory = dirname($savePath);
                Log::info("保存图片目录：" . $directory);
                if (!is_dir($directory)) {
                    mkdir($directory, 0755, true);
                }

                // 保存图片文件
                $saved = file_put_contents($savePath, $imageData);
                if ($saved === false) {
                    throw new \Exception("图片保存失败");
                }

                return true;
            } else {
                $errMsg = isset($result['errMsg']) ? $result['errMsg'] : '下载失败';
                throw new \Exception($errMsg);
            }
        } catch (\Exception $e) {
            Log::error("保存图片到文件异常：" . $e->getMessage());
            throw $e;
        }
    }

    /**
     * 生成3DES密钥的核心方法
     * @return string
     * @throws \Exception
     */
    public static function generate3DESKeyCore() {
        $keyLength = 24; // DESede 密钥实际为 24 字节（对应 168 位有效位）
        $key = openssl_random_pseudo_bytes($keyLength, $strong);
        if ($key === false || !$strong) {
            throw new \Exception("生成随机字符串异常：无法生成强加密强度的密钥");
        }
        return $key;
    }

    /**
     * 生成3DES密钥
     * @return string 48位十六进制密钥
     * @throws \Exception
     */
    public static function generate3DESKey(){
        return bin2hex(self::generate3DESKeyCore());
    }

    public function decrptByPem($dgtlEnvlp){
        $pkcs12 = file_get_contents($this->PFX_FILE_PATH);
        $PfxPathStr = array();
        if (openssl_pkcs12_read($pkcs12, $PfxPathStr, $this->KEY_PWD)) {
            $PrivateKey = $PfxPathStr['pkey'];
        } else {
            throw new \Exception("私钥读取异常【密码和证书不匹配】！");
        }
        return NewRsaUtil1::decrptByPem($dgtlEnvlp,$PrivateKey);
    }
}
